import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import md5 from 'md5'
import { reqLogin } from "@/apis/user";
import type { UserResponseData, UserResponseDataEncrypt } from "@/apis/user/type"
import { Config } from '@/config';
import type { Router } from 'vue-router';
// 加密本地存储
import SecureLS from 'secure-ls'
// 重写LocalStorage
import type { StorageLike } from 'pinia-plugin-persistedstate';
// 自定义加密密钥
const ls = new SecureLS({encodingType: 'rc4', isCompression: false, encryptionSecret: Config.STORAGE_ENCRYPTION_SECRET as string})
const CustomLocalStorage: typeof StorageLike = {
  setItem(key: string, value: string) {
    ls.set(key, value)
  },
  getItem(key: string): string | null {
    return ls.get(key)
  }
}
import { rsaDecrypt } from '@/utils/rsaEncrypt';
export const useUserStore = defineStore('user', () => {
  // 本地存储token
  let token = ref<string>('');
  let sid = ref<string>('');
  let isLogin = computed<boolean>(() => !!token.value);
  // 登录逻辑
  async function login(userInfo: { userName: string, password: string }) {
    let passwordMd5 = md5(userInfo.password);
    let userName = userInfo.userName;
    let res: UserResponseDataEncrypt = await reqLogin({ userName: userName, password: passwordMd5 });
    if (res.code === 200) { 
      const decryptData:UserResponseData = rsaDecrypt(res.data.data);
      sid.value = decryptData.sid;      
      token.value = decryptData.token;
    }
    return res;
  }
  // token过期逻辑
  function clearUserInfo(router:Router) {
    token.value = '';
    sid.value = '';
    localStorage.removeItem(Config.USER_STORAGE_KEY)
    router.push('/login');
  }
  return { token, sid, isLogin, login, clearUserInfo }
}, {
  persist: {
    key: Config.USER_STORAGE_KEY as string,
    paths: ['token', 'sid'],
    storage: CustomLocalStorage,
    debug: import.meta.env.MODE === 'development',
    beforeRestore: (ctx) => {      
      console.log('beforeRestore', ctx);
    },
    afterRestore: (ctx) => {
      console.log('afterRestore', ctx);
    }
  }
})
